package com.zjbti.contentp;

import static android.text.TextUtils.replace;

import android.annotation.SuppressLint;
import android.content.ContentProvider;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rv_contact;
    private ContactAdapter adapter;
    @Override
    //程序创建时的方法
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        init();
    }

    //
    private void init(){
        rv_contact = findViewById(R.id.rv_contact);
        rv_contact.setLayoutManager(new LinearLayoutManager(this));
        getPermissions();
    }

    //判断那些权限没有 然后发起申请权限
    String[] permissionlist;
    public void getPermissions(){
        if ( android.os.Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
//            需要的权限列表
            permissionlist = new String[]{"android.permission.READ_CONTACTS"};
            //未授权的列表
            ArrayList<String> list = new ArrayList<>();
            //循环判断需要的权限列表中未授权的权限，然后添加到未授权列表中
            for(int i=0;i<permissionlist.length;i++){
                if(ActivityCompat.checkSelfPermission(this,permissionlist[i])!= PackageManager.PERMISSION_GRANTED){
                    list.add(permissionlist[i]);
                }
            }
            if(list.size()>0){
                ActivityCompat.requestPermissions(this,list.toArray(new String[list.size()]),1);
            }else{
                Toast.makeText(this,"未找到列表数据",Toast.LENGTH_SHORT).show();
                setData();
            }
        }else{
            setData();
        }
    }

    //获取授权结果，即是否成功
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        if(requestCode==1){
            for(int i=0;i<permissions.length;i++){
                if(permissions[i].equals("android.permission.READ_CONTACTS")
                        && grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"读取通讯录权限申请成功",Toast.LENGTH_SHORT).show();
                    setData();
                }else{
                    Toast.makeText(this,"读取通讯录权限申请失败",Toast.LENGTH_SHORT).show();

                }
            }
        }
    }

    //
    private void setData(){
        List<ContactInfo> contactInfos = getContacts();
        adapter = new ContactAdapter(MainActivity.this,contactInfos);
        rv_contact.setAdapter(adapter);
    }

    //
    @SuppressLint("Range")
    public List<ContactInfo> getContacts(){
        List<ContactInfo> contactInfos = new ArrayList<>();
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        //清除集合中数据
        if(contactInfos!=null){
            contactInfos.clear();
        }
        while(cursor.moveToNext()){
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            int isHas =  Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if(isHas>0){
                Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id,null,null);
                while(c.moveToNext()){
                    ContactInfo info = new ContactInfo();
                    info.setContactName(name);
                    String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).trim();
                    number=number.replace(" ","").replace("-","").replace("(","").replace(")","");
                    info.setPhoneNumber(number);
                    contactInfos.add(info);
                }
                c.close();
            }

        }
        cursor.close();
        return contactInfos;
    }
}